%%
% Perform prinicipal component analysis on an NxM input matrix X, where:
% N - the number of variables
% M - the number of observations (number of samples)
% Returns the first <NumFeaturesToUse> principal components of X, skipping 
% the first <NumFeaturesToSKip>.
% The function is caching the PCA calculation results in file. In order to
% properly use it, please use the same description for the same matrix.
% For example: X1trainMinusX2train
%
% Notice: this function is taking care of transposing X and transposing it back

function [ EigenVectors, MeanX ] = PerformPCA(X, X_Description)
	sFilename = [ X_Description, '_princomp.mat' ];

	fprintf('PerformPCA: Cache file name: %s\n', sFilename);
	if ~exist(sFilename,'file')
		fprintf('PerformPCA: Cache file not found, calculating and caching\n');
		[ COEFF, SCORE, latent ] = princomp(X');
		save(sFilename, 'COEFF', 'SCORE', 'latent');
	else
		fprintf('PerformPCA: Loading from cache\n');
		load(sFilename, 'COEFF');
	end;
	fprintf('PerformPCA: PCA calculation done\n');

	MeanX = mean(X, 2);
	EigenVectors = COEFF;
	%TransformedX = (X' * TopEigenVectors)';
end
